﻿
Imports System.Threading
Imports std
Imports storoomc

Public Class jobuploader_t
    Private jobs As list(Of String) = Nothing
    Private locker As sequentialLock = Nothing
    Private timer3Index As Guid = Guid.Empty
    Private storoom As storoomTalk = Nothing
    Private storoomlocker As duallock = Nothing

    Private Sub lock()
        locker.wait()
    End Sub

    Private Sub unlock()
        locker.release()
    End Sub

    Public Function insert(ByVal p As progress) As Boolean
        If Not p Is Nothing Then
            Dim rtn As Boolean = Nothing
            lock()
            rtn = jobs.push_back(Convert.ToString(p))
            unlock()
            Return rtn
        Else
            Return False
        End If
    End Function

    Private Sub configChanged()
        storoomlocker.lock()
        storoom.initial(config.uploadJobInfoStoroomAddress.Address, config.uploadJobInfoStoroomAddress.Port)
        storoomlocker.unlock()
    End Sub

    Public Sub close()
        'speed up the uploading progress
        While Not jobs.empty()
            upload()
        End While
    End Sub

    Private Sub upload()
        Dim s As String = Nothing
        lock()
        If Not jobs.empty() Then
            copy(s, jobs.front())
            jobs.pop_front()
        End If
        unlock()

        If Not isemptystring(s) Then
            storoomlocker.wait()
            If Not storoom.write(jobinfoStoroomKey, encoding.utf8().GetBytes(s)) Then
                raiseError("cannot write jobinfo " + s + " to storoom " + _
                           Convert.ToString(config.uploadJobInfoStoroomAddress), errorHandle.errorType.exclamation)
            End If
            storoomlocker.release()
        End If
    End Sub

    Public Sub New()
        jobs = New list(Of String)()
        locker = New sequentialLock()
        storoom = New storoomTalk()
        storoomlocker = New duallock()
        timer3Index = timer3.addcall(AddressOf upload, secondsToMilliseconds(1))
        AddHandler distrrun.configChanged, AddressOf configChanged
    End Sub

    Protected Overrides Sub Finalize()
        If timer3Index <> Guid.Empty Then
            assert(timer3.removecall(timer3Index))
            timer3Index = Guid.Empty
        End If
        MyBase.Finalize()
    End Sub
End Class